<template>
  <div class="shrink-box no-drag">
    <div class="box-full round-4 overflow-hidden bgfff">
      <div class="box-full flex-col bgfff box-border px-20 overflow-hidden pb-14">
        <div class="flex flex-a-c flex-j-b w-full mb-20 pt-20 pr-20">
          <a-input-search
            v-model="searchValue"
            allow-clear
            style="width: 40%"
            size="large"
            placeholder="输入群名称检索"
          />
          <a-space>
            <a-button type="primary" @click="handleOpenSetting(true)">
              <template #icon>
                <icon-pause />
              </template>
              全部开启
            </a-button>
            <a-button type="primary" @click="handleOpenSetting(false)">
              <template #icon>
                <icon-play-arrow />
              </template>
              全部暂停
            </a-button>
            <a-button type="primary" :disabled="!selectedKeys?.length" @click="handleClearSetting">
              <template #icon>
                <icon-close />
              </template>
              批量清除设置
            </a-button>
            <a-button
              type="primary"
              status="warning"
              :loading="loading"
              @click="getWxGroupList(true)"
            >
              <template #icon>
                <icon-refresh />
              </template>
              刷新群列表
            </a-button>
          </a-space>
        </div>
        <div class="w-full flex-1 m-relative">
          <div class="m-absolute t-0 b-0 r-0 l-0 overflow-hidden" ref="tableBox">
            <a-table
              v-model:columns="columns"
              v-model:selectedKeys="selectedKeys"
              :data="tableData"
              row-key="wxid"
              :bordered="false"
              :loading="loading"
              :pagination="false"
              :scroll="{ y: '100%' }"
              :row-selection="{ type: 'checkbox', showCheckedAll: true }"
            >
              <template #groupInfo="{ rowIndex, record }">
                <div class="flex flex-a-c">
                  <!-- <div class="w-30 mr-4 flex flex-j-c">{{ rowIndex + 1 }}</div> -->
                  <a-image
                    width="42"
                    height="42"
                    class="mx-4"
                    :preview="false"
                    style="border-radius: 4px"
                    :src="record.avatar"
                  />
                  <span class="ml-6">{{ record.nickname }}</span>
                </div>
              </template>
              <template #sourceInfo="{ record }">
                <div class="flex flex-a-c">
                  <div class="border-theme">
                    <a-button type="text" @click="handleOpenGroup(record, record.wxid)">
                      <template #icon>
                        <icon-plus size="20" />
                      </template>
                    </a-button>
                  </div>
                  <template v-if="record.followSetting">
                    <div class="flex flex-a-c m-relative">
                      <a-image
                        width="42"
                        height="42"
                        class="mx-4"
                        :preview="false"
                        style="border-radius: 4px"
                        :src="record.followSetting.avatar"
                      />
                      <span class="ml-6 flex-1">{{ record.followSetting.nickname }}</span>
                      <div
                        class="ml-6 h-18 round-4 text-size-12 flex-center px-6 no-wrap"
                        :class="record.followSetting.type == 1 ? 'g-group' : 'm-group'"
                      >
                        {{ record.followSetting.type == 1 ? '官方' : '我的' }}
                      </div>
                      <div
                        class="m-absolute cursor-pointer"
                        :style="{ top: '-6px', right: '-14px' }"
                        @click="handleClearSettingItem(record)"
                      >
                        <icon-close-circle style="color: red" size="18" />
                      </div>
                    </div>
                  </template>
                </div>
              </template>
              <template #compere="{ record }">
                <template v-if="record.followSetting">
                  <span v-if="record.followSetting.type == 1">--</span>
                  <div v-else class="flex flex-a-c">
                    <div class="border-theme mr-6">
                      <a-button type="text" @click="handleOpenMember(record, record.wxid)">
                        <template #icon>
                          <icon-plus size="20" />
                        </template>
                      </a-button>
                    </div>
                    <div class="flex flex-a-c flex-wrap">
                      <div
                        class="flex flex-a-c"
                        v-for="(item, index) in record.followSetting.Member"
                        :key="item.wxid"
                      >
                        <div class="text666 nowrap w-fit">{{ item.nickname }}</div>
                        <a-divider
                          direction="vertical"
                          v-if="index != record.followSetting.Member.length - 1"
                        />
                      </div>
                    </div>
                  </div>
                </template>
              </template>
              <!-- <template #preview="{ record }">
                <template v-if="record.followSetting">
                  <a-button type="text" status="warning">
                    <template #icon>
                      <icon-eye />
                    </template>
                    <template #default>预览</template>
                  </a-button>
                </template>
              </template> -->
              <template #status="{ record }">
                <template v-if="record.followSetting">
                  <a-switch
                    v-model="record.followSetting.isOpen"
                    @change="handleSwitchChange($event, record)"
                  />
                </template>
              </template>
            </a-table>
          </div>
        </div>
      </div>
    </div>
    <groupModal
      ref="groupModalRef"
      :officialGroupList="officialGroupList"
      :personalGroupList="personalGroupList"
      @handleSourceSuccess="handleSourceSuccess"
    />
    <MemberModal ref="memberModalRef" @handleChooseMember="handleChooseMember"></MemberModal>
  </div>
</template>

<script setup>
import {
  IconRefresh,
  IconPlus,
  IconPause,
  IconPlayArrow,
  IconClose,
  IconCloseCircle
} from '@arco-design/web-vue/es/icon'
import $bus from '@renderer/common/js/bus'
import { Message, Modal } from '@arco-design/web-vue'
import groupModal from './groupModal.vue'
import MemberModal from './memberModal.vue'
let weixinInfo = null
const { ipcRenderer } = window.electron
const loading = ref(false)
const tableBox = ref()
const officialGroupList = ref([])
const personalGroupList = ref([])
const groupModalRef = ref()
const memberModalRef = ref()
const currentGroup = ref()
let tableDataO = reactive([])
const searchValue = ref()
const tableData = computed(() => {
  if (searchValue.value) {
    return tableDataO.filter((item) => item.nickname.includes(searchValue.value))
  } else {
    return tableDataO.slice() // 使用 slice() 创建 tableDataO 的浅拷贝
  }
})
const selectedKeys = ref([])
const columns = [
  {
    title: '转发群',
    slotName: 'groupInfo',
    width: 180
  },
  {
    title: '源头群(单选)',
    slotName: 'sourceInfo',
    width: 200,
    filterable: {
      filters: [
        {
          text: '有跟群设置',
          value: 1
        },
        {
          text: '无跟群设置',
          value: 0
        }
      ],
      filter: (value, record) => {
        const status = record.followSetting ? 1 : 0
        console.log(status, value)
        return status == value[0]
      }
    }
  },
  {
    title: '主持人',
    slotName: 'compere',
    width: 200
  },
  // {
  //   title: '预览',
  //   slotName: 'preview',
  //   align: 'center',
  //   width: 80
  // },
  {
    title: '开启',
    slotName: 'status',
    width: 70
  }
]

// 刷新源头群
const getWxGroupList = (flag = false) => {
  loading.value = true
  ipcRenderer.send('getWxGroupList')
  ipcRenderer.send('sendToWebSocket', { wsMsgType: 'getSourceChatroom' })
  setTimeout(() => {
    if (loading.value) loading.value = false
  }, 3000)
}

// 监听群列表消息
ipcRenderer.on('recvWxGroupList', async (event, message) => {
  personalGroupList.value = JSON.parse(JSON.stringify(message))
  const followSetting = await window.ipcRenderer.invoke('storeGet', 'followSetting')
  let followSettingRe = followSetting?.[weixinInfo.wxid]
  if (followSettingRe && JSON.stringify(followSettingRe) !== '{}') {
    message.forEach((item) => {
      if (!followSettingRe[item.wxid]) {
        item['followSetting'] = undefined
      } else {
        item['followSetting'] = followSettingRe[item.wxid]
      }
    })
  }
  tableDataO.splice(0, tableDataO.length, ...message)
  if (loading.value) loading.value = false
})

// 监听WebSocket消息
ipcRenderer.on('webSocketMessage', async (event, res) => {
  if (res?.data?.wsMsgType) {
    switch (res?.data?.wsMsgType) {
      case 'getSourceChatroom':
        if (res.code == 200) {
          const list = res.data?.list ?? []
          officialGroupList.value = list
        } else {
          Message.error(res.message)
        }
        break
    }
  }
})

// 点击更换源头群
const handleOpenGroup = (record, id) => {
  currentGroup.value = id
  groupModalRef.value?.chooseSource(record)
}

// 点击更换源头群成员
const handleOpenMember = (record, id) => {
  currentGroup.value = id
  memberModalRef.value?.openMemberModal2(record)
}

// 源头群选择成功，通知更改数据
const handleSourceSuccess = async (res) => {
  const index = tableDataO.findIndex((item) => item.wxid === currentGroup.value)
  const resultO = { ...res, isOpen: false }
  tableDataO[index].followSetting = resultO
  let followSetting = await window.ipcRenderer.invoke('storeGet', 'followSetting')
  if (!followSetting) followSetting = {}
  if (!followSetting[weixinInfo.wxid]) followSetting[weixinInfo.wxid] = {}
  if (!followSetting[weixinInfo.wxid][currentGroup.value])
    followSetting[weixinInfo.wxid][currentGroup.value] = {}
  const result = JSON.parse(JSON.stringify(resultO))
  followSetting[weixinInfo.wxid][currentGroup.value] = result
  ipcRenderer.send('getSetting', {
    data: followSetting,
    result: followSetting[weixinInfo.wxid],
    type: 'followSetting'
  })

  window.ipcRenderer.invoke('storeSet', 'followSetting', followSetting)
  Message.success('源头已更换,请手动再次开启')
}

// 选择群成员的回调
const handleChooseMember = async (val) => {
  const index = tableDataO.findIndex((item) => item.wxid === currentGroup.value)
  const resultO = { ...tableDataO[index].followSetting, Member: val, isOpen: false }
  tableDataO[index].followSetting = resultO
  let followSetting = await window.ipcRenderer.invoke('storeGet', 'followSetting')
  if (!followSetting) followSetting = {}
  if (!followSetting[weixinInfo.wxid]) followSetting[weixinInfo.wxid] = {}
  if (!followSetting[weixinInfo.wxid][currentGroup.value])
    followSetting[weixinInfo.wxid][currentGroup.value] = {}
  const result = JSON.parse(JSON.stringify(resultO))
  followSetting[weixinInfo.wxid][currentGroup.value] = result
  ipcRenderer.send('getSetting', {
    data: followSetting,
    result: followSetting[weixinInfo.wxid],
    type: 'followSetting'
  })
  window.ipcRenderer.invoke('storeSet', 'followSetting', followSetting)
  Message.success('成员已更换,请手动再次开启')
}

// 切换跟群开关
const handleSwitchChange = async (e, record) => {
  const index = tableDataO.findIndex((item) => item.wxid === record.wxid)
  const resultO = { ...tableDataO[index].followSetting, isOpen: e }
  tableDataO[index].followSetting = resultO
  let followSetting = await window.ipcRenderer.invoke('storeGet', 'followSetting')
  const result = JSON.parse(JSON.stringify(resultO))
  followSetting[weixinInfo.wxid][record.wxid] = result
  ipcRenderer.send('getSetting', {
    data: followSetting,
    result: followSetting[weixinInfo.wxid],
    type: 'followSetting'
  })
  window.ipcRenderer.invoke('storeSet', 'followSetting', followSetting)
  Message.success(`跟发已${e ? '开启' : '关闭'},立即生效`)
}

//批量清除设置
const handleClearSetting = () => {
  Modal.warning({
    title: '提示',
    content: '是否确认将当前选中的跟群设置删除？',
    hideCancel: false,
    onOk: async () => {
      let followSetting = await window.ipcRenderer.invoke('storeGet', 'followSetting')
      selectedKeys.value.forEach((item) => {
        const index = tableDataO.findIndex((ele) => {
          return ele.wxid === item
        })
        if (index != -1) {
          const wxid = tableDataO[index].wxid
          if (followSetting?.[weixinInfo.wxid]?.[wxid]) {
            delete followSetting[weixinInfo.wxid][wxid]
          }
          tableDataO[index].followSetting = undefined
        }
      })
      ipcRenderer.send('getSetting', {
        data: followSetting,
        result: followSetting?.[weixinInfo.wxid] ?? {},
        type: 'followSetting'
      })
      await window.ipcRenderer.invoke('storeSet', 'followSetting', followSetting)
      selectedKeys.value = []
      Message.success('操作成功')
    }
  })
}

// 单个清除
const handleClearSettingItem = async (record) => {
  let followSetting = await window.ipcRenderer.invoke('storeGet', 'followSetting')
  const index = tableDataO.findIndex((ele) => {
    return ele.wxid === record.wxid
  })
  if (index != -1) {
    tableDataO[index].followSetting = undefined
    const wxid = tableDataO[index].wxid
    if (followSetting?.[weixinInfo.wxid]?.[wxid]) {
      delete followSetting[weixinInfo.wxid][wxid]
    }
  }
  ipcRenderer.send('getSetting', {
    data: followSetting,
    result: followSetting?.[weixinInfo.wxid] ?? {},
    type: 'followSetting'
  })
  await window.ipcRenderer.invoke('storeSet', 'followSetting', followSetting)
  Message.success('操作成功')
}

// 全部开始/暂停
const handleOpenSetting = (flag) => {
  Modal.warning({
    title: '提示',
    content: `是否确认将当前所有跟群设置全部${flag ? '开启' : '暂停'}？`,
    hideCancel: false,
    onOk: async () => {
      let followSetting = await window.ipcRenderer.invoke('storeGet', 'followSetting')
      let followSettingRe = followSetting?.[weixinInfo.wxid] ?? {}
      if (!followSettingRe || JSON.stringify(followSettingRe) == '{}') return Message('未设置跟群')
      for (const key in followSettingRe) {
        followSettingRe[key]['isOpen'] = flag
      }
      tableDataO.forEach((item) => {
        if (!!followSettingRe[item.wxid]) {
          item.followSetting['isOpen'] = flag
        }
      })
      followSetting[weixinInfo.wxid] = followSettingRe
      window.ipcRenderer.invoke('storeSet', 'followSetting', followSetting)
      ipcRenderer.send('getSetting', {
        data: followSetting,
        result: followSettingRe,
        type: 'followSetting'
      })
      Message.success('操作成功')
    }
  })
}

onMounted(async () => {
  weixinInfo = await window.ipcRenderer.invoke('storeGet', 'weixinInfo')
  getWxGroupList(false)
  $bus.on('getWxGroupList', async () => {
    // 监听到切换微信则重置跟群设置
    weixinInfo = await window.ipcRenderer.invoke('storeGet', 'weixinInfo')
    const followSetting = await window.ipcRenderer.invoke('storeGet', 'followSetting')
    const followSettingRe = followSetting?.[weixinInfo.wxid]
    if (followSettingRe && JSON.stringify(followSettingRe) !== '{}') {
      for (const key in followSettingRe) {
        followSettingRe[key]['isOpen'] = false
      }
    }
    followSetting[weixinInfo.wxid] = followSettingRe || {}
    ipcRenderer.send('getSetting', {
      data: followSetting,
      result: followSettingRe ?? {},
      type: 'followSetting'
    })
    await window.ipcRenderer.invoke('storeSet', 'followSetting', followSetting)
    getWxGroupList(false)
  })
})

onUnmounted(() => {
  $bus.off('getWxGroupList')
})
</script>
<style scope lang="scss">
.shrink-box {
  width: 100%;
  height: 100%;
  overflow: hidden;
  border: 1px solid #eee;
  box-sizing: border-box;
  padding: 10px;
  background: #ececec;
}
.g-group {
  color: #ff8d1a;
  border: rgba(255, 141, 26, 1) solid 1px;
  background-color: rgba(255, 141, 26, 0.1);
}
.m-group {
  color: rgba(42, 130, 228, 1);
  background-color: rgba(42, 130, 228, 0.1);
  border: rgba(42, 130, 228, 1) solid 1px;
}
</style>
